package com.hello.system.controller;

import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hello.common.log.annotation.Log;
import com.hello.common.log.enums.BusinessType;
import com.hello.common.security.annotation.RequiresPermissions;
import com.hello.system.domain.FishDetectionResult;
import com.hello.system.service.IFishDetectionResultService;
import com.hello.common.core.web.controller.BaseController;
import com.hello.common.core.web.domain.AjaxResult;
import com.hello.common.core.utils.poi.ExcelUtil;
import com.hello.common.core.web.page.TableDataInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 鱼类检测结果详情Controller
 * 
 * @author hello
 * @date 2025-09-11
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/fishDetectionResult")
public class FishDetectionResultController extends BaseController
{
    private final IFishDetectionResultService fishDetectionResultService;

    /**
     * 查询鱼类检测结果详情列表
     */
    @RequiresPermissions("system:fishDetectionResult:list")
    @GetMapping("/list")
    public TableDataInfo list(FishDetectionResult fishDetectionResult)
    {
        startPage();
        List<FishDetectionResult> list = fishDetectionResultService.selectFishDetectionResultList(fishDetectionResult);
        return getDataTable(list);
    }

    /**
     * 导出鱼类检测结果详情列表
     */
    @RequiresPermissions("system:fishDetectionResult:export")
    @Log(title = "鱼类检测结果详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FishDetectionResult fishDetectionResult)
    {
        List<FishDetectionResult> list = fishDetectionResultService.selectFishDetectionResultList(fishDetectionResult);
        ExcelUtil<FishDetectionResult> util = new ExcelUtil<FishDetectionResult>(FishDetectionResult.class);
        util.exportExcel(response, list, "鱼类检测结果详情数据");
    }

    /**
     * 获取鱼类检测结果详情详细信息
     */
    @RequiresPermissions("system:fishDetectionResult:query")
    @GetMapping(value = "/{resultId}")
    public AjaxResult getInfo(@PathVariable("resultId") Long resultId)
    {
        return success(fishDetectionResultService.selectFishDetectionResultByResultId(resultId));
    }

    /**
     * 新增鱼类检测结果详情
     */
    @RequiresPermissions("system:fishDetectionResult:add")
    @Log(title = "鱼类检测结果保存", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FishDetectionResult fishDetectionResult)
    {
        try {
            // 清理可能的控制字符，避免操作日志记录异常
            if (fishDetectionResult.getAdditionalInfo() != null) {
                String cleanInfo = fishDetectionResult.getAdditionalInfo().replaceAll("[\u0000-\u001f]", "");
                fishDetectionResult.setAdditionalInfo(cleanInfo);
            }
            
            // 详细打印检测结果信息
            printDetectionResultDetails(fishDetectionResult);
            
            int result = fishDetectionResultService.insertFishDetectionResult(fishDetectionResult);
            
            if (result > 0) {
                log.info("🎉 鱼类检测结果保存成功！");
            } else {
                log.error("❌ 鱼类检测结果保存失败！");
            }
            
            return toAjax(result);
            
        } catch (Exception e) {
            log.error("❌ 保存鱼类检测结果异常: {}", e.getMessage());
            return error("保存失败: " + e.getMessage());
        }
    }
    
    /**
     * 打印检测结果详细信息
     */
    private void printDetectionResultDetails(FishDetectionResult result) {
        log.info("🐟 ================================ 鱼类检测结果详情 ================================");
        log.info("📋 基本信息:");
        log.info("   ├─ 结果ID: {}", result.getResultId());
        log.info("   ├─ 视频ID: {}", result.getVideoId());
        log.info("   ├─ 模型ID: {}", result.getModelId());
        log.info("   ├─ 批次ID: {}", result.getDetectionBatchId());
        log.info("   ├─ 帧ID: {}", result.getFrameId());
        log.info("   ├─ 检测时间戳: {}", result.getDetectionTime());
        log.info("   ├─ 置信度阈值: {}", result.getConfidenceThreshold());
        log.info("   └─ 会话开始时间: {}", result.getSessionStartTime());
        
        log.info("🎯 检测信息:");
        log.info("   ├─ 检测置信度: {}%", result.getConfidence());
        log.info("   ├─ 置信度等级: {}", result.getConfidenceLevel());
        log.info("   └─ 检测质量: {}", result.getDetectionQuality());
        
        log.info("📐 位置信息:");
        log.info("   ├─ 边界框坐标: X={}, Y={}", result.getBboxX(), result.getBboxY());
        log.info("   ├─ 边界框尺寸: {}×{} pixels", result.getBboxWidth(), result.getBboxHeight());
        log.info("   ├─ 中心点坐标: ({}, {})", result.getCenterX(), result.getCenterY());
        log.info("   ├─ 边界框面积: {} px²", result.getBboxArea());
        log.info("   └─ 长宽比: {}", result.getAspectRatio());
        
        log.info("🐠 物种信息:");
        log.info("   ├─ 鱼类物种: {}", result.getSpecies());
        log.info("   └─ 物种类别: {}", result.getSpeciesCategory());
        
        if (result.getEstimatedLength() != null || result.getEstimatedHeight() != null || result.getEstimatedWeight() != null) {
            log.info("📏 尺寸信息:");
            if (result.getEstimatedLength() != null) {
                log.info("   ├─ 估算体长: {} cm", result.getEstimatedLength());
            }
            if (result.getEstimatedHeight() != null) {
                log.info("   ├─ 估算体高: {} cm", result.getEstimatedHeight());
            }
            if (result.getEstimatedWeight() != null) {
                log.info("   ├─ 估算体重: {} g", result.getEstimatedWeight());
            }
            if (result.getSizeConfidence() != null) {
                log.info("   └─ 尺寸置信度: {}", result.getSizeConfidence());
            }
        }
        
        if (result.getEstimatedAge() != null || result.getAgeStage() != null || result.getHealthStatus() != null) {
            log.info("🧬 生物特征:");
            if (result.getEstimatedAge() != null) {
                log.info("   ├─ 估算年龄: {} 岁", result.getEstimatedAge());
            }
            if (result.getAgeStage() != null) {
                log.info("   ├─ 生长阶段: {}", result.getAgeStage());
            }
            if (result.getHealthStatus() != null) {
                log.info("   ├─ 健康状态: {}", result.getHealthStatus());
            }
            if (result.getConditionFactor() != null) {
                log.info("   └─ 体况系数: {}", result.getConditionFactor());
            }
        }
        
        if (result.getActivity() != null || result.getEstimatedSpeed() != null || result.getDirection() != null) {
            log.info("🏊 行为信息:");
            if (result.getActivity() != null) {
                log.info("   ├─ 活动状态: {}", result.getActivity());
            }
            if (result.getEstimatedSpeed() != null) {
                log.info("   ├─ 当前游速: {} m/s", result.getEstimatedSpeed());
            }
            if (result.getMaxSwimSpeed() != null) {
                log.info("   ├─ 最大游速: {} cm/s", result.getMaxSwimSpeed());
            }
            if (result.getOrientation() != null) {
                log.info("   ├─ 游泳朝向: {}°", result.getOrientation());
            }
            if (result.getDirection() != null) {
                log.info("   └─ 游泳方向: {}", result.getDirection());
            }
        }
        
        if (result.getAdditionalInfo() != null && !result.getAdditionalInfo().isEmpty()) {
            log.info("📄 扩展信息: {}", result.getAdditionalInfo().length() > 100 ? 
                    result.getAdditionalInfo().substring(0, 100) + "..." : result.getAdditionalInfo());
        }
        
        log.info("🐟 ===============================================================================");
    }

    /**
     * 修改鱼类检测结果详情
     */
    @RequiresPermissions("system:fishDetectionResult:edit")
    @Log(title = "鱼类检测结果详情", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FishDetectionResult fishDetectionResult)
    {
        return toAjax(fishDetectionResultService.updateFishDetectionResult(fishDetectionResult));
    }

    /**
     * 删除鱼类检测结果详情
     */
    @RequiresPermissions("system:fishDetectionResult:remove")
    @Log(title = "鱼类检测结果详情", businessType = BusinessType.DELETE)
	@DeleteMapping("/{resultIds}")
    public AjaxResult remove(@PathVariable Long[] resultIds)
    {
        return toAjax(fishDetectionResultService.deleteFishDetectionResultByResultIds(resultIds));
    }
}
